﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobiShop.Models;

namespace MobiShop.Controllers
{ 
    [MyAuthorize(MyRole = 2)]
    public class AdminOrderController : Controller
    {
        public static int perItemPage = 6;

        private MobishopEntities db = new MobishopEntities();

        //
        // GET: /AdminOrder/

        public ActionResult Index(FindOrderData find, int id = 1)
        {
            if (id <= 0) return HttpNotFound(); // ko xử lý khi yêu cầu trang ko hợp lệ
            
            if (!ModelState.IsValid)
            {
                return View(find);
            }

            ViewBag.QueryString = Request.Url.Query;
            ViewBag.OrderStatusIdSelectedValue = find.OrderStatusId;
            if (find.visible == true)
                ViewBag.VisibleSelectedValue = "true";
            else if (find.visible == false) ViewBag.VisibleSelectedValue = "false";
            else ViewBag.VisibleSelectedValue = "";

            // ra lệnh tìm kiếm
            var orderlist = find.Find(db);

            // ok, phân trang

            int SoKetQua = orderlist.Count();
            int p = SoKetQua / perItemPage;
            if (SoKetQua % perItemPage != 0)
            {
                p = p + 1;
            }

            ViewBag.SoKetQua = SoKetQua;
            ViewBag.CurrentPage = id;
            ViewBag.page = p;
            ViewBag.OrderList = orderlist.OrderBy(s=>s.id).Skip((id - 1) * perItemPage).Take(perItemPage).ToList();

            return View(find);
        }

        //
        // GET: /AdminOrder/Edit/5

        // kiểm tra link đã thực hiện redirect tới để tạo có thể tạo đúng link quay về
        private string GetReturnUrl()
        {
            string defaultUrl =  "/AdminOrder/Index";
            if (Request.UrlReferrer == null) return defaultUrl;

            string AbsolutePath = Request.UrlReferrer.AbsolutePath;
            char[] phanCach = {'/'};
            string[] kq = AbsolutePath.Split(phanCach);
            if (kq.Length < 2) return defaultUrl;
            
            int id;
            if(int.TryParse(kq[kq.Length-1], out id))// trường hợp link có id
            {
                if(kq.Length<3 || kq[kq.Length-3].ToLower() != "adminorder" 
                    || kq[kq.Length-2].ToLower() != "index") return defaultUrl;
                return defaultUrl+"/"+kq[kq.Length-1]+Request.UrlReferrer.Query;
            }
            // nguược lại, link ko có id:
            if(kq[kq.Length-2].ToLower() != "adminorder" || kq[kq.Length-1].ToLower() != "index")
                return defaultUrl;
            return defaultUrl+Request.UrlReferrer.Query;
        }
 
        public ActionResult Edit(int id)
        {
            ViewBag.ReturnUrl = GetReturnUrl();
            
            Order order;
            try
            {
                order = db.OrderList.Single(o => o.id == id);
            }
            catch (System.Exception)
            {
                return HttpNotFound();
            }

            ViewBag.orderStatusList = new SelectList(db.OrderStatusList, "id", "name", order.orderStatusId);
            List<SelectListItem> VisibleList = AppSetting.Make_Clone(AppSetting.VisibleListItem, null);
            VisibleList[0].Text = "NULL";
            ViewBag.VisibleList = VisibleList;
            return View(order);
        }

        //
        // POST: /AdminOrder/Edit/5

        [HttpPost]
        public ActionResult Edit(Order order, string SaveReturnUrl, FormCollection form)
        {
            Order currentOrder;
            try
            {
                currentOrder = db.OrderList.Single(o => o.id == order.id);
            }
            catch (System.Exception)
            {
                return HttpNotFound();
            }
            currentOrder.receiveName = order.receiveName;
            currentOrder.receiveAddress = order.receiveAddress;
            currentOrder.receivePhoneNumber = order.receivePhoneNumber;
            currentOrder.receiveIdentityCardNumber = order.receiveIdentityCardNumber;
            currentOrder.orderStatusId = order.orderStatusId;
            currentOrder.receiveDate = order.receiveDate;
            currentOrder.visible = order.visible;
            order = currentOrder;

            if (SaveReturnUrl == null)
                ViewBag.ReturnUrl = "/AdminOrder/Index";
            else ViewBag.ReturnUrl = SaveReturnUrl;

            if (ModelState.IsValid)
            {
                db.SaveChanges();
                Response.Redirect((string)ViewBag.ReturnUrl);
                return null;
            }else ViewBag.ThongBao = "Cập nhật thất bại!";

            ViewBag.orderStatusList = new SelectList(db.OrderStatusList, "id", "name", order.orderStatusId);
            List<SelectListItem> VisibleList = AppSetting.Make_Clone(AppSetting.VisibleListItem, null);
            VisibleList[0].Text = "NULL";
            ViewBag.VisibleList = VisibleList;
            return View(order);
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}